<template>
  <a-modal
    title="产品选择"
    width="70%"
    :visible="visible"
    :confirmLoading="loading"
    okText="选择"
    @ok="handleChoose"
    @cancel="
      () => {
        this.visible = false
      }
    "
  >
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.KeyWord" placeholder="编号/名称" />
            </a-form-item>
          </a-col>
          <a-col :md="20" :sm="24">
            <a-button
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin-left: 8px" @click="() => ((queryParam = {}), getDataList())">重置</a-button>
            <a-radio-group style="margin-left: 8px" v-model="urlType" button-style="solid" @change="changeRadio">
              <a-radio-button value="a"> 材料 </a-radio-button>
              <a-radio-button value="b"> 成本项 </a-radio-button>
            </a-radio-group>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      v-if="urlType == 'a'"
      :scroll="{ y: scroll }"
      :columns="columns"
      :rowKey="(row, index) => row.cInvCode"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: type }"
      :bordered="true"
      size="small"
    >
      <template slot="dataIndex" slot-scope="text, record, index">
        <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
      </template>
    </a-table>
    <a-table
      v-else
      ref="table"
      :scroll="{ y: scroll }"
      :columns="treeColumns"
      :rowKey="(row, index) => row.Id"
      :dataSource="treeData"
      :pagination="treePagination"
      :loading="loading"
      @change="handleTreeTableChange"
      @expand="handleTableExpand"
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        type: type,
        getCheckboxProps: getCheckboxProps,
      }"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a v-if="hasPerm('cost_term.Edit')" @click="handleEdit(record.Id)">编辑</a>
          <a-divider v-if="hasPerm('cost_term.Edit') && hasPerm('cost_term.Delete')" type="vertical" />
          <a v-if="hasPerm('cost_term.Delete')" @click="handleDelete([record.Id])">删除</a>
        </template>
      </span>
    </a-table>
  </a-modal>
</template>

<script>
const columns = [
  { title: '产品编号', dataIndex: 'cInvCode' },
  { title: '产品名称', dataIndex: 'cInvName' },
  { title: '规格', dataIndex: 'cInvStd' },
]
const treeColumns = [
  { title: '成本项名称', dataIndex: 'CostName', align: 'center' },
  { title: '备注', dataIndex: 'Remark', align: 'center' },
]
export default {
  props: {
    type: { type: String, default: 'radio', required: false },
    // cid: { type: String, required: false }
  },
  watch: {
    // cid(n, o) {
    //   //console.log(n)
    // }
  },
  components: {
    // EnumName,
    // EnumSelect
  },
  mounted() {
    this.getDataList()
  },
  data() {
    return {
      urlType: 'a',
      data: [],
      pagination: {
        current: 1,
        pageSize: 25,
        pageSizeOptions: ['25', '50', '100'],
        showSizeChanger: true,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
      },
      filters: {},
      sorter: { field: 'cInvCode', order: 'desc' },
      loading: false,
      columns,
      queryParam: {},
      selectedRowKeys: [],
      selectedRows: [],
      visible: false,
      // 树表格
      treeColumns,
      treeData: [],
      treePagination: {
        current: 1,
        pageSize: 25,
        pageSizeOptions: ['25', '50', '100'],
        showSizeChanger: true,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
      },
    }
  },
  computed: {
    scroll() {
      return Number(document.documentElement.clientHeight) * 0.45
    },
  },
  methods: {
    getCheckboxProps(record) {
      return {
        props: {
          disabled: !record.isLeaf, // Column configuration not to be checked
        },
      }
    },
    handleTableExpand(expanded, record) {
      console.log(expanded, record)
      if (expanded) {
        if (record.children.length) {
          return
        }
        this.loading = true
        this.$http.post('/CostManagement/cost_term/GetCost_TermList?ParentId=' + record.Id, {}).then((res) => {
          res.Data.forEach((item) => {
            this.loading = false

            if (item.isLeaf) {
              this.$set(item, 'children', null)
            } else {
              this.$set(item, 'children', [])
            }
          })
          record.children = res.Data
        })
      }
    },
    changeRadio(e) {
      if (e == 'a') this.getDataList()
      else this.getTreeDataList()
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    handleTreeTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getTreeDataList()
    },
    getDataList(cInvCode) {
      // this.selectedRowKeys = []
      // this.selectedRows = []
      this.loading = true
      this.$http
        .post('/CostManagement/inventoryall/GetDataList', {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'cInvCode',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false
          this.data = resJson.Data
          const pagination = { ...this.pagination }
          pagination.total = resJson.Total
          this.pagination = pagination
        })
    },
    getTreeDataList(id = '') {
      this.selectedRowKeys = []
      this.loading = true
      this.$http
        .post('/CostManagement/cost_term/GetCost_TermList?ParentId=' + id, {
          PageIndex: this.pagination.current,
          PageRows: this.pagination.pageSize,
          SortField: this.sorter.field || 'Id',
          SortType: this.sorter.order,
          Search: this.queryParam,
          ...this.filters,
        })
        .then((resJson) => {
          this.loading = false

          if (resJson.Total) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
          resJson.Data.forEach((item) => {
            if (item.isLeaf) {
              item.children = null
            } else {
              item.children = []
            }
          })
          this.treeData = resJson.Data
        })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    openChoose() {
      this.selectedRows = []
      this.selectedRowKeys = []
      this.getDataList()
      this.visible = true
    },
    handleChoose() {
      if (this.selectedRows.length <= 0) return this.$message.error('请选择')
      this.visible = false
      this.$emit('onChoose', this.selectedRows)
    },
  },
}
</script>
